package com.hoyue.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hoyue.bean.Video;
import com.hoyue.service.VideoService;

@WebServlet("/VideoServlet")
public class VideoServlet extends HttpServlet {

    VideoService videoService = new VideoService();
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("method");//获取方法名
        if(name == null || name.isEmpty()){
            throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
        }
        Class c = this.getClass();//获得当前类的Class对象
        Method method = null;
        try {
            //获得Method对象
            method = getClass().getDeclaredMethod(name, HttpServletRequest.class,HttpServletResponse.class);
        } catch (Exception e) {
            throw new RuntimeException("没有找到"+name+"方法，请检查该方法是否存在");
        }

        try {
            method.invoke(this, request,response);//反射调用方法
        } catch (Exception e) {
            System.out.println("你调用的方法"+name+",内部发生了异常");
            throw new RuntimeException(e);
        }

    }
    protected void getVideo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Video Videos = videoService.getVideo();
        request.setAttribute("video", Videos);
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

    protected void getAdminVideo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Video Videos = videoService.getVideo();
        request.setAttribute("video", Videos);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/admin/video.jsp").forward(request, response);
    }

    protected void updateVideo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String url = request.getParameter("url");
            String title = request.getParameter("title");
            String presentation = request.getParameter("presentation");
            VideoService videoService = new VideoService();
            Video video = new Video();
            video.setId(1);
            video.setAddress(url);
            video.setTitle(title);
            video.setPresentation(presentation);
            videoService.updateIntro(video);
            System.out.println(url);
            request.getRequestDispatcher(request.getContextPath() + "/VideoServlet?method=getAdminVideo").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}